import React, { useEffect, useRef } from 'react';
import {
    View,
    Image,
    Text,
    StyleSheet,
    Animated,
} from 'react-native';
import { BlurView } from '@react-native-community/blur';
import { useHeaderHeight } from '@react-navigation/elements';
import { connect } from 'react-redux';
import coverRight from '@/assets/cover-right.png';
import Tab from './tab';
import {
    PanGestureHandler,
    State,
    TapGestureHandler,
} from 'react-native-gesture-handler';
import { viewportHeight } from '@/utils/index';

const mapStateToProps = ({ album }) => {
    return {
        summary: album.summary,
        author: album.author,
        list: album.list,
    };
};

const connector = connect(mapStateToProps);

const HEADER_HEIGHT = 260;
const USE_NATIVE_DRIVER = true;

function Album(props) {
    const { dispatch, navigation, list, route, headerHeight, summary, author, } = props;
    const { id, title, image } = route.params.item;
    // console.log('viewportHeight', viewportHeight)
    const panRef = useRef(null)
    const tapRef = useRef(null)
    const nativeRef = useRef(null)
    const RANGE = [-(HEADER_HEIGHT - headerHeight), 0];
    const translationY = new Animated.Value(0);
    const lastScrollY = new Animated.Value(0);
    lastScrollYValue = 0;
    reverseLastScrollY = Animated.multiply(
        new Animated.Value(-1),
        lastScrollY,
    );
    translationYValue = 0;
    translationYOffset = new Animated.Value(0);
    translateY = Animated.add(
        Animated.add(translationY, reverseLastScrollY),
        translationYOffset,
    );
    useEffect(() => {
        dispatch({
            type: 'album/fetchAlbum',
            payload: {
                id,
            },
        });
        navigation.setParams({
            opacity: translateY.interpolate({
                inputRange: RANGE,
                outputRange: [1, 0],
            }),
        });
    }, [])

    const onItemPress = (data, index) => {
        const previousItem = list[index - 1];
        const nextItem = list[index + 1];
        dispatch({
            type: 'player/setState',
            payload: {
                previousId: previousItem ? previousItem.id : '',
                nextId: nextItem ? nextItem.id : '',
                title: data.title,
                thumbnailUrl: route.params.item.image,
                sounds: list.map(item => ({ id: item.id, title: item.title })),
            },
        });
        navigation.navigate('Detail', { id: data.id });
    };

    const onScrollDrag = Animated.event(
        [{ nativeEvent: { contentOffset: { y: lastScrollY } } }],
        {
            useNativeDriver: !!USE_NATIVE_DRIVER,
            listener: ({ nativeEvent }) => {
                lastScrollYValue = nativeEvent.contentOffset.y;
            },
        },
    );

    const onGestureEvent = Animated.event(
        [{ nativeEvent: { translationY: translationY } }],
        {
            useNativeDriver: !!USE_NATIVE_DRIVER,
        },
    );

    const onHandlerStateChange = ({ nativeEvent }) => {
        if (nativeEvent.oldState === State.ACTIVE) {
            let { translationY } = nativeEvent;
            translationY -= lastScrollYValue;
            translationYOffset.extractOffset();
            translationYOffset.setValue(translationY);
            translationYOffset.flattenOffset();
            translationY.setValue(0);
            translationYValue += translationY;
            let maxDeltaY = -RANGE[0] - translationYValue;
            if (translationYValue < RANGE[0]) {
                translationYValue = RANGE[0];
                Animated.timing(translationYOffset, {
                    toValue: RANGE[0],
                    useNativeDriver: !!USE_NATIVE_DRIVER,
                }).start();
                maxDeltaY = RANGE[1];
            } else if (translationYValue > RANGE[1]) {
                translationYValue = RANGE[1];
                Animated.timing(translationYOffset, {
                    toValue: RANGE[1],
                    useNativeDriver: !!USE_NATIVE_DRIVER,
                }).start();
                maxDeltaY = -RANGE[0];
            }
            if (tapRef.current) {
                const tap = tapRef.current;
                tap.setNativeProps({
                    maxDeltaY,
                });
            }
        }
    };

    renderHeader = () => {
        return (
            <View style={[styles.header, { paddingTop: headerHeight }]}>
                <Image source={{ uri: image }} style={styles.background} />
                {/* <BlurView
                    blurType="light"
                    blurAmount={10}
                    style={StyleSheet.absoluteFillObject}
                /> */}
                <View style={styles.leftView}>
                    <Image source={{ uri: image }} style={styles.thumbnail} />
                    <Image source={coverRight} style={styles.coverRight} />
                </View>
                <View style={styles.rightView}>
                    <Text style={styles.title}>{title}</Text>
                    <View style={styles.summary}>
                        <Text numberOfLines={1} style={styles.summaryText}>
                            {summary}
                        </Text>
                    </View>
                    <View style={styles.author}>
                        {author.avatar ? <Image source={{ uri: author.avatar }} style={styles.avatar} /> : <Text></Text>}
                        <Text style={styles.name}>{author.name}</Text>
                    </View>
                </View>
            </View>
        );
    };

    return (
        <TapGestureHandler ref={tapRef} maxDeltaY={-RANGE[0]}>
            <View style={styles.container}>
                <PanGestureHandler
                    ref={panRef}
                    simultaneousHandlers={[tapRef, nativeRef]}
                    onGestureEvent={onGestureEvent}
                    onHandlerStateChange={onHandlerStateChange}>
                    <Animated.View
                        style={[
                            styles.container,
                            {
                                transform: [
                                    {
                                        translateY: translateY.interpolate({
                                            inputRange: RANGE,
                                            outputRange: RANGE,
                                            extrapolate: 'clamp',
                                        }),
                                    },
                                ],
                            },
                        ]}>
                        {renderHeader()}
                        <View style={{ height: viewportHeight - headerHeight }}>
                            <Tab
                                panRef={panRef}
                                tapRef={tapRef}
                                nativeRef={nativeRef}
                                onScrollDrag={onScrollDrag}
                                onItemPress={onItemPress}
                            />
                        </View>
                    </Animated.View>
                </PanGestureHandler>
            </View>
        </TapGestureHandler>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    header: {
        height: HEADER_HEIGHT,
        flexDirection: 'row',
        paddingHorizontal: 20,
        alignItems: 'center',
    },
    background: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: '#eee',
    },
    leftView: {
        marginRight: 26,
    },
    thumbnail: {
        width: 98,
        height: 98,
        borderColor: '#fff',
        borderWidth: StyleSheet.hairlineWidth,
        borderRadius: 8,
        backgroundColor: '#fff',
    },
    coverRight: {
        height: 98,
        position: 'absolute',
        right: -23,
        resizeMode: 'contain',
    },
    rightView: {
        flex: 1,
    },
    title: {
        color: '#fff',
        fontSize: 18,
        fontWeight: '900',
    },
    summary: {
        backgroundColor: 'rgba(0, 0, 0, 0.3)',
        padding: 10,
        marginVertical: 10,
        borderRadius: 4,
    },
    summaryText: {
        color: '#fff',
    },
    author: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    avatar: {
        height: 26,
        width: 26,
        borderRadius: 13,
        marginRight: 8,
    },
    name: {
        color: '#fff',
    },
});


function Wrapper(props) {
    const headerHeight = useHeaderHeight();
    return <Album headerHeight={headerHeight} {...props} />;
}

export default connector(Wrapper);
